package com.yixing.demo.controller;

import com.yixing.demo.component.JwtClass;
import com.yixing.demo.constants.Constants;
import com.yixing.demo.model.User;
import com.yixing.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@Slf4j
@RestController
public class UserController {
    //不能加static修饰，否则配置文件的内容注入不进来
    private String SAVE_PATH = "/home/ubuntu/chat_in_different_dimensions/";

    @Resource
    UserService userService;

    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/login")
    public Object login(String username, String password, HttpSession session) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return new User();
        }
        User userInfo = userService.login(username);
        if(userInfo == null) {
            return new User();
        }
        if(bCryptPasswordEncoder.matches(password, userInfo.getPassword())) {
            Map<String,Object> map = new HashMap<>();
            map.put(Constants.USER_ID, userInfo.getUserId());
            map.put(Constants.USER_NAME, userInfo.getUsername());
            String token = JwtClass.getToken(map);
            userInfo.setToken(token);
            userInfo.setPassword("");
            session.setAttribute(Constants.USER_SESSION, userInfo);
            return userInfo;
        }else {
            return new User();
        }
    }

    @RequestMapping("/register")
    public Object register(User user) {
        if(!StringUtils.hasLength(user.getUsername()) || !StringUtils.hasLength(user.getPassword())) {
            return new User();
        }
        String encodePassword = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        try{
             userService.register(user);
        }catch (DuplicateKeyException e) {
              log.error("注册失败");
              return new User();
        }
        user.setPassword("");
        return user;
    }

    @RequestMapping("/getuserInfo")
    public Object getuserInfo(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if(session == null) {
            log.info("获取不到session对象");
            return new User();
        }
        User userInfo = (User)session.getAttribute(Constants.USER_SESSION);
        if(userInfo == null) {
            log.info("获取不到user对象");
            return new User();
        }
        userInfo.setPassword("");
        return userInfo;
    }

    @RequestMapping("/upload")
    public Object upload(MultipartFile file, HttpServletRequest req) {
        String titleAndType = file.getOriginalFilename();
        if(titleAndType.equals("")) {
            return false;
        }
        String localFilePath = SAVE_PATH + titleAndType;
        System.out.println(localFilePath);
        File localFile = new File(localFilePath);
        if (!localFile.exists()) {
            localFile.mkdirs();
        }
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        HttpSession session = req.getSession(false);
        User userInfo = (User) session.getAttribute(Constants.USER_SESSION);
        try {
            userService.uploadAvatar(localFilePath, userInfo.getUserId());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            localFile.delete();//这一步一定要写
            return false;
        }
    }

    @RequestMapping("/getavatar")
    public ResponseEntity<byte[]> play(String username, HttpServletRequest req) {
        if(username == null) {
            HttpSession session = req.getSession(false);
            User userInfo = (User)session.getAttribute(Constants.USER_SESSION);
            String avatarPath = userService.selectAvatar(userInfo.getUserId());
            if(avatarPath == null) {
                return null;
            }else {
                try {
                    byte[] bytes = Files.readAllBytes(new File(avatarPath).toPath());
                    return ResponseEntity.ok(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;//这个返回一定要有
                }
            }
        }else {
            String avatarPath = userService.selectAvatarByUsername(username);
            if(avatarPath == null) {
                return null;
            }else {
                try {
                    byte[] bytes = Files.readAllBytes(new File(avatarPath).toPath());
                    return ResponseEntity.ok(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;//这个返回一定要有
                }
            }
        }
    }
}
